from flask import Flask, request
import config
from flask_caching import Cache
from blueprints import register_blueprints
import logger
import logging

# 创建应用日志记录器
app_logger = logger.get_module_logger('app')

# 设置根日志记录器级别为INFO，确保能看到所有INFO级别的日志
logging.basicConfig(level=logging.INFO)

app = Flask(__name__)

# 加载配置文件
app.config.from_object(config)

# 初始化缓存
cache = Cache(app)

# 自动注册所有蓝图
register_blueprints(app)

# 设置静态文件缓存控制
@app.after_request
def after_request(response):
    # 为静态文件添加缓存控制头
    if request.endpoint and 'static' in request.endpoint:
        response.cache_control.max_age = 3600  # 缓存1小时
        response.cache_control.public = True
    return response

# 请求日志
@app.before_request
def log_request():
    app_logger.info(f"收到请求: {request.method} {request.url}")

# 响应日志
@app.after_request
def log_response(response):
    app_logger.info(f"响应状态: {response.status_code} for {request.method} {request.url}")
    return response

# 错误日志
@app.errorhandler(Exception)
def handle_exception(e):
    app_logger.error(f"应用错误: {str(e)}", exc_info=True)
    return "Internal Server Error", 500

if __name__ == '__main__':
    app_logger.info("正在启动 QnBt 应用...")
    app.run(debug=True, host='0.0.0.0')